package com.example.security.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author linzp
 * @date 2022/2/16 9:29
 */
@Slf4j
public class JwtUtil {

    public static void main(String[] args) {
        jwtUtil();
    }

    public static void jwt() {
        String sign = JWT.create()
                .setPayload("id", "12345")
                .setPayload("name", "Lin")
                .setKey("qwer".getBytes())
                .setExpiresAt(Date.from(LocalDateTime.now().plusSeconds(10).atZone(ZoneId.systemDefault()).toInstant()))
                .setNotBefore(new Date())
                .sign();
        log.info("生成token ：{}", sign);
        JWT of = JWT.of(sign);
        JWTHeader header = of.getHeader();
        log.info("header: {}", header);
        Object id = of.getPayload("id");
        Object name = of.getPayload("name");
        log.info("payload >> id:{}、name:{}", id, name);
        log.warn("token 校验：{}", of.setKey("qwer".getBytes()).verify());
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.warn("token 校验：{}", of.setKey("qwer".getBytes()).validate(3));
    }

    public static void jwtUtil() {
        Map<String, Object> payload = new HashMap<>();
        payload.put("id", "12345");
        payload.put("name", "Lin");
        String token = JWTUtil.createToken(payload, "qwer".getBytes());
        log.info("生成token ：{}", token);
        JWT jwt = JWTUtil.parseToken(token);
        log.info("header: {}", jwt.getHeader());
        log.info("payload: {}", jwt.getPayload());

    }
}
